package com.wanxi.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class GetSqlSession {
    private static ThreadLocal<SqlSession> local = new ThreadLocal<SqlSession>();

    public static SqlSession getSqlSession() {
        String resource = "mybatis-config.xml";
        SqlSessionFactory sqlSessionFactory = null;
        SqlSession sqlSession = local.get();
        try {
            if (sqlSession == null) {
//            打开资源文件
                InputStream inputStream = Resources.getResourceAsStream(resource);
//            开启sqlsession
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

//                事务控制：一般用在批量提交
                sqlSession = sqlSessionFactory.openSession(true);
                local.set(sqlSession);//问题：没有将我们的sqlsession放入local
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return sqlSession;
    }

    /**
     * 事物提交
     */
    public static void commit() {
        if (local.get() != null) {
            local.get().commit();
            local.get().close();
            local.set(null);
        }
    }

    public static void rollback() {
        if (local.get() != null) {
            local.get().commit();
            local.get().close();
            local.set(null);
        }
    }
}
